package com.huike.framework.aspectj;

import com.alibaba.fastjson.JSON;
import com.huike.clues.domain.SysOperLog;
import com.huike.common.annotation.Log;
import com.huike.common.core.domain.model.LoginUser;
import com.huike.common.enums.BusinessStatus;
import com.huike.common.enums.HttpMethod;
import com.huike.common.utils.ServletUtils;
import com.huike.common.utils.StringUtils;
import com.huike.common.utils.ip.IpUtils;
import com.huike.common.utils.spring.SpringUtils;
import com.huike.framework.manager.AsyncManager;
import com.huike.framework.manager.factory.AsyncFactory;
import com.huike.framework.web.service.TokenService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

/**
 * 操作日志记录处理
 */
//todo 开发阶段关闭日志, 上线之前放开下面两个注释
//@Aspect
//@Component
public class LogAspect {

    // 配置织入点
    @Pointcut("@annotation(com.huike.common.annotation.Log)")
    public void logPointCut() {
    }


    /**
     * 使用环绕通知实现日志记录
     *
     * @param pjp
     * @return
     */
    @Around(value = "logPointCut()")
    public Object handlerLog(ProceedingJoinPoint pjp) {
        Object obj = null;
        SysOperLog operLog = new SysOperLog();

        try {
            // 获取当前的用户
            LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());

            //基本日志
            operLog.setStatus(BusinessStatus.SUCCESS.ordinal());//状态
            operLog.setOperIp(IpUtils.getIpAddr(ServletUtils.getRequest()));//客户端ip
            operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());//请求URL
            if (loginUser != null) {
                operLog.setOperName(loginUser.getUsername());//操作用户
            }
            String className = pjp.getTarget().getClass().getName();
            String methodName = pjp.getSignature().getName();
            operLog.setMethod(className + "." + methodName + "()");//获取访问的类和方法
            operLog.setRequestMethod(ServletUtils.getRequest().getMethod());//请求方式


            Log log = ((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(Log.class);//获取方法上的Log注解
            if (log != null) {
                operLog.setBusinessType(log.businessType().ordinal());// 设置action动作
                operLog.setTitle(log.title());// 设置标题
                operLog.setOperatorType(log.operatorType().ordinal());// 设置操作人类别
                // 是否需要保存request，参数和值
                if (log.isSaveRequestData()) {
                    String requestMethod = operLog.getRequestMethod();
                    if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
                        String params = argsArrayToString(pjp.getArgs());
                        operLog.setOperParam(StringUtils.substring(params, 0, 2000));
                    } else {
                        Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest()
                                .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
                        operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
                    }

                }
            }

            //执行切点方法
            obj = pjp.proceed();

            // 返回参数
            operLog.setJsonResult(JSON.toJSONString(obj));

            return obj;
        } catch (Throwable t) {
            operLog.setStatus(BusinessStatus.FAIL.ordinal());//设置失败状态
            operLog.setErrorMsg(StringUtils.substring(t.getMessage(), 0, 2000));//设置失败消息
            throw new RuntimeException(t);
        } finally {
            // 保存数据库
            AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
        }
    }


    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (int i = 0; i < paramsArray.length; i++) {
                if (!isFilterObject(paramsArray[i])) {
                    Object jsonObj = JSON.toJSON(paramsArray[i]);
                    params += jsonObj.toString() + " ";
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
                return iter.next() instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
                Map.Entry entry = (Map.Entry) iter.next();
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }
}
